package com.dindang.checkline.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.view.ViewTreeObserver;

import com.dindang.checkline.R;
import com.dindang.checkline.app.utils.AddPicUtils;
import com.dindang.checkline.app.utils.BitnapUtils;
import com.dindang.checkline.mvp.model.entity.BaseResponse;
import com.dindang.checkline.mvp.model.entity.ErrorEntity;
import com.dindang.checkline.mvp.model.entity.TaskEvent;
import com.dindang.checkline.mvp.ui.activity.adapter.costom.GridImageAdapter;
import com.dindang.checkline.mvp.ui.activity.witget.FullyGridLayoutManager;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.dindang.checkline.mvp.contract.ErrorEndingContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.utils.DateTimeUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/26/2019 10:12
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class ErrorEndingPresenter extends BasePresenter<ErrorEndingContract.Model, ErrorEndingContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private GridImageAdapter mGridImageAdapter;
    private AddPicUtils mAddPicUtils;
    private int imageWidth = 0;
    private int maxSelectNum = 1;// 图片最大可选择数
    private String id;//任务单的id
    private WaitDialog mWaitDialog;
    private ErrorEntity.ErrorParam mParam = new ErrorEntity.ErrorParam();
    TaskEvent taskEvent = new TaskEvent();
    private static final String compressImageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/esl/Compress/"; // 图片及其他数据保存文件夹
   private String imgUrl;
    @Inject
    public ErrorEndingPresenter(ErrorEndingContract.Model model, ErrorEndingContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        id = mRootView.getActivity().getIntent().getStringExtra("id");
        initSelectImage();//设置图片
        mRootView.getButtonSbumit().setOnClickListener(v -> postData());
    }

    private void postData() {//点击提交,提交异常原因接口
        if(mRootView.getEtRemark().getText().toString().isEmpty()){
            ArmsUtils.makeText(mRootView.getActivity(),"请输入异常原因");
            return;
        }
        //以下是真实调接口
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mParam.reMark = mRootView.getEtRemark().getText().toString();
        mParam.recordId = id+"";//任务id
        mParam.dClose = DateTimeUtils.dateToYearMonthDayHour(new Date(System.currentTimeMillis()));
        if(mAddPicUtils.selectList!=null&&mAddPicUtils.selectList.size()>0){
            imgUrl = BitnapUtils.compressImage(mAddPicUtils.selectList.get(0).getCompressPath(), compressImageFilePath + System.currentTimeMillis() + ".jpg", 40);
           File file = new File(mAddPicUtils.selectList.get(0).getCompressPath());
            try {
                InputStream inputStream = new FileInputStream(file);
                List<byte[]> bytes = new ArrayList<>();
                byte[] bytes1=new byte[inputStream.available()];
                mParam.cPhoto.add(bytes1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mModel.submitError(mParam)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mWaitDialog.hideWaitingDialog();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(response.isSuccess()){
                           ArmsUtils.makeText(mRootView.getActivity(),response.getStatuMsg());
                            mRootView.getActivity().finish();
                            EventBus.getDefault().post(taskEvent);
                        }
                    }
                });
    }

    private void initSelectImage() {
        mRootView.getTvCheckNumTip().setText("可选，最多支持添加" + maxSelectNum + "张图片");
        setPicRemainNumTip(0);
        mAddPicUtils = new AddPicUtils(mRootView.getActivity());
        mAddPicUtils.setSelectMax(maxSelectNum);
        mGridImageAdapter = new GridImageAdapter(mRootView.getRecyclerView().getContext(), mAddPicUtils.onAddPicClickListener);
        mGridImageAdapter.setList(mAddPicUtils.selectList);
        mGridImageAdapter.setSelectMax(maxSelectNum);
        mRootView.getRecyclerView().setAdapter(mGridImageAdapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mRootView.getRecyclerView().getContext(), 4, GridLayoutManager.VERTICAL, false);
        mRootView.getRecyclerView().setLayoutManager(manager);
        ViewTreeObserver vto = mRootView.getRecyclerView().getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (imageWidth == 0) {
                    imageWidth = mRootView.getRecyclerView().getMeasuredWidth();
                    mGridImageAdapter.setImageWidth(imageWidth);
                }
                return true;
            }
        });

        mGridImageAdapter.setOnRemainNumListener(new GridImageAdapter.OnRemainNumListener() {
            @Override
            public void onItemClick(int remainNum) {
                setPicRemainNumTip(remainNum);
            }
        });
    }

    /**
     * activity回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mRootView.getActivity().RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                mAddPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                mGridImageAdapter.setList(mAddPicUtils.selectList);
                mGridImageAdapter.notifyDataSetChanged();
                setPicRemainNumTip(mAddPicUtils.selectList.size());
                break;
        }
    }

    private void setPicRemainNumTip(int remain) {
        mRootView.getTvCheckNum().setText(remain + "/" + maxSelectNum);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mGridImageAdapter = null;
        this.mAddPicUtils = null;
    }
}
